<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-button type="primary" @click="dialogVisible = true">新增角色</el-button>
            <el-table :data="dataList" style="width: 100%" border @expand-change="expandHandle()">
                <el-table-column prop="index" label="#" width="180" type="expand">
                    <template slot-scope="scope">
                        <el-row v-for="(item, index) in scope.row.permissionList" :key="item.id"
                            :class="[borderRight, index === 0 ? borderTop : '']" class="jaja">
                            <el-col :span="9"><el-tag closable>{{ item.name }} </el-tag><i
                                    class="el-icon-caret-right"></i></el-col>
                            <el-col :span="15">
                                <el-row v-for="item1 in item.children" :key="item1.id" class="erji"
                                    :class="[borderTop]">
                                    <el-col :span="7">
                                        <el-tag type="success" closable>{{ item1.name }} </el-tag>
                                    </el-col>
                                    <el-col :span="17">
                                        <el-row v-for="item2 in item1.children" :key="item2.id" class="sanji">
                                            <el-tag type="waring" closable @close="closeWindow(item2, item1)">{{
                                                item2.name
                                                }} </el-tag>
                                        </el-row>
                                    </el-col>
                                </el-row>
                            </el-col>


                        </el-row>



                    </template>

                </el-table-column>

                <el-table-column prop="index" label="序号" width="180" type="index"></el-table-column>
                <el-table-column prop="name" label="姓名" width="180">
                </el-table-column>
                <el-table-column prop="des" label="描述">
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">

                        <el-button type="primary" @click="updateUser(scope.row)">编辑</el-button>

                        <el-button type="danger" @click="deleteRole(scope.row)">删除</el-button>
                        <el-button type="info" @click="asignPerssion(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>

            </el-table>

            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :page-sizes="[1, 2, 3, 4]" :page-size="user.pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="user.total">
            </el-pagination>
        </el-card>




        <el-dialog title="新增角色" :visible.sync="dialogVisible" width="30%">
            <el-form label-width="80px" :model="role" :rules="rules" ref="ruleForm">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="role.name"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="des">
                    <el-input v-model="role.des"></el-input>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole()">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog title="编辑角色" :visible.sync="dialogVisibleUpdate" width="30%">
            <el-form label-width="80px" :model="role" :rules="rules" ref="ruleForm">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="role.name"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="des">
                    <el-input v-model="role.des"></el-input>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleUpdate = false">取 消</el-button>
                <el-button type="primary" @click="editRole()">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog title="编辑权限" :visible.sync="assignPersion" width="30%" @close="closeDialog()">
            <el-tree :data="permissionChildrenList" :props="defaultProps" show-checkbox default-expand-all
                :default-checked-keys="defKeys" node-key='id' ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="assignPersion = false">取 消</el-button>
                <el-button type="primary" @click="editPermission()">确 定</el-button>
            </span>
        </el-dialog>
    </div>



</template>
<script>
import { getRoleList, addRole, updateRoleById, deleteRoleById, deletePermissionId, permissionChildrenList, updatePermissionByRoleId, getPermissionByRoleId } from '@/api/Permission.js';


export default {
    name: 'roleList',
    data() {

        var validateName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入角色名字'));
            } else {

                callback();
            }
        };


        var validateDes = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入角色描述'));
            } else {

                callback();
            }
        };
        return {
            //权限树
            permissionChildrenList: [],

            defaultProps: {
                children: 'children',
                label: 'name'
            },
            defKeys: [],

            dataList: [],
            user: { pageNum: 1, pageSize: 1, total: 10 },
            total: 10,
            dialogVisible: false,
            dialogVisibleUpdate: false,
            borderRight: 'borderRight',
            borderTop: 'borderTop',
            assignPersion: false,
            //当前操作的roleId
            selectRoleId: 0,
            // 当前操作的节点
            selectNode: {},



            role: {
                id: '',
                name: '',
                desc: ''
            }, rules: {
                name: [
                    { validator: validateName, trigger: 'blur' }
                ],
                des: [
                    { validator: validateDes, trigger: 'blur' }
                ],

            }
        }
    }, methods: {
        selectRole() {

            getRoleList(this.user).then(res => {
                console.log(res);

                this.dataList = res.data.data.list;
                this.user.total = res.data.data.total;

            })

        }, handleSizeChange(val) {
            this.user.pageSize = val;

            this.selectRole();

        }, currentPage4(val) {
            this.user.pageNum = val;
            this.selectRole();
        }, handleCurrentChange(val) {
            this.user.pageNum = val;
            this.selectRole();
        }, addRole() {
            this.$refs.ruleForm.validate(res => {

                console.log(res)

            })
            console.log("添加角色,", this)
            addRole(this.role).then(res => {
                console.log("添加角色完成,", res)
            })
            console.log("添加角色,", this)
            this.selectRole();
            this.dialogVisible = false;
        }, updateUser(row) {
            this.dialogVisibleUpdate = true;
            this.role = row;

        }, editRole() {

            updateRoleById(this.role);
            this.selectRole();
            this.dialogVisibleUpdate = false;

        }, deleteRole(row) {
            this.$confirm('确定删除' + row.name + "吗", '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {


                deleteRoleById(row);
                this.total -= 1;
                this.selectRole()


            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }, toggleRowExpansion(row) {
            console.log("折叠的数目", row)
        }, expandHandle() {
            // alert("改变")
        }, closeWindow(row, parent) {

            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deletePermissionId(row).then(res => {
                    console.log('res', res);
                    parent.children = res.data.data;
                })
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });

            })
        }, getChildNode(node, defkyesList) {
            // 防御性编程：统一处理数组/对象输入
            const nodes = Array.isArray(node) ? node : [node];

            nodes.forEach(dto => {
                // 检查节点有效性
                if (!dto || typeof dto !== 'object') return;

                // 处理叶子节点
                if (!dto.children || dto.children.length === 0) {
                    if (dto.id !== undefined) {
                        return defkyesList.push(dto.id);
                    }
                    // return;
                }

                // 递归处理子节点
                this.getChildNode(dto.children, defkyesList);
            });
        }

        , asignPerssion(row) {
            this.assignPersion = true;
            //所有的权限列表
            permissionChildrenList().then(res => {
                this.permissionChildrenList = res.data.data;

                console.log("权限列表", this.permissionChildrenList);
                this.getChildNode(row.permissionList, this.defKeys);

                console.log("当前节点", row.permissionList);
                console.log("需要填充的节点：" + this.defKeys);
                this.selectRoleId = row.id;
                this.selectNode = row;
            })



        }, editPermission() {
            const selectNodeIds = this.$refs.treeRef.getCheckedNodes(false, true);
            console.log("选中的节点id{}", selectNodeIds.id);

            const idArray = selectNodeIds.map(item => item.id);

            console.log("选中的id的数组", idArray);
            let persion = { roleId: this.selectRoleId, permissionId: idArray }

            console.log("修改权限需要传递的参数{} ", persion);

            updatePermissionByRoleId(persion);


            //修改完后，重新获取角色下的权限,放入defkeys中去
            let roleParm = { id: this.selectRoleId }


            getPermissionByRoleId(roleParm).then(res => {
                this.defKeys = res.data.data[0].permissionList.map(item => item.id);
            })

            this.assignPersion = false;

        }, closeDialog() {
            this.defKeys = [];

            console.log("关闭弹窗事件{}", this.defKeys)
        }



    }
    , created() {
        this.selectRole();



    }

}

// 在此添加组件的其他逻辑
</script>
<style scoped lang="less">
.el-table {
    margin-top: 10px;
}

/* 在此添加组件的样式 */
.el-pagination {
    display: flex;
    justify-content: center;
    margin-top: 10px;
}

.el-card {
    margin-top: 10px;
}



.borderRight {
    margin: 7px;
    border-bottom: 1px solid beige;
}

.borderTop {
    border-top: 1px solid beige;
    border-right: 1px solid beige;
}

.erji {
    margin: 5px;
    // border-bottom: 1px solid beige;
}

.sanji {
    margin: 5px;
    // border-bottom: 1px solid beige;
    float: left;
    /* 左浮动实现横向排列 */
    clear: none;
    /* 确保不强制换行 */
    width: auto;
    /* 宽度自适应内容 */
}

.jaja {
    display: flex;
    align-items: center;
}
</style>